const path = require("path");
const fs = require('fs');

const CSS_EXT = ['.css', '.scss', '.sass', '.less', '.styl', '.wxss', '.acss', '.ttss', '.qss']
const SCSS_EXT = ['.scss']
const JS_EXT = ['.js', '.jsx']
const TS_EXT = ['.ts', '.tsx']

const REG_SCRIPT = /\.(js|jsx)(\?.*)?$/
const REG_TYPESCRIPT = /\.(tsx|ts)(\?.*)?$/
const REG_STYLE = /\.(css|scss|sass|less|styl|wxss)(\?.*)?$/
const REG_MEDIA = /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/
const REG_IMAGE = /\.(png|jpe?g|gif|bpm|svg|webp)(\?.*)?$/
const REG_FONT = /\.(woff2?|eot|ttf|otf)(\?.*)?$/
const REG_JSON = /\.json(\?.*)?$/

module.exports = class ReplaceModuleRequestPlugin {
  constructor(option) {
    this.includes = option.includes;
  }

  apply(compiler) {
    compiler.hooks.normalModuleFactory.tap(
      "ReplaceModuleRequestPlugin",
      (factory) => {
        factory.hooks.beforeResolve.tap(
          "ReplaceModuleRequestPlugin",
          (resolveData) => {
            const { context, request } = resolveData;
            const absPath = path.join(
              context,
              request
            );
            const extName = path.extname(absPath);
            if (REG_SCRIPT.test(extName) || REG_TYPESCRIPT.test(extName)) {
              // js
            } else if (REG_JSON.test(extName)) {
              // json
            } else if (REG_FONT.test(extName) || REG_IMAGE.test(extName) || REG_MEDIA.test(extName)) {
              // 媒体文件
            } else if (REG_STYLE.test(extName)) {
              // 样式文件
            } else {
              const newReq = this.resolveScriptPath(absPath);
              resolveData.request = newReq;
            }
          }
        );
      }
    );
  }

  resolveScriptPath = (p) => {
    const realPath = p;
    const PLATFORM_ENV = process.PLATFORM_ENV;
    const SCRIPT_EXT = JS_EXT.concat(TS_EXT)
    for (let i = 0; i < SCRIPT_EXT.length; i++) {
      const item = SCRIPT_EXT[i]
      if (PLATFORM_ENV) {
        // 指定到文件
        if (fs.existsSync(`${p}.${PLATFORM_ENV}${item}`)) {
          return `${p}.${PLATFORM_ENV}`
        }
        // 目录默认取目录下index文件
        if (fs.existsSync(`${p}${path.sep}index.${PLATFORM_ENV}${item}`)) {
          return `${p}${path.sep}index.${PLATFORM_ENV}`
        }
      }
    }
    return realPath
  }
};
